package com.example.miaosha.service;

import com.example.miaosha.entity.SeLoanRecord;
import com.example.miaosha.mapper.SeLoanRecordMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author
 * @Date 2022/2/22 17:09
 */
@Slf4j
@Service
public class SeLoanRecordService {

    @Resource
    private SeLoanRecordMapper seLoanRecordMapper;


    /**
     * 查找用户 贷款记录（逾期记录）
     *
     * @param userId
     * @return
     */
    public Boolean screenRecord(String userId) {
        log.info("查询用户逾期记录【开始】,查找的用户ID为：{}", userId);
        Calendar calendar = Calendar.getInstance();
        Date date = new Date();
        log.info("当前时间为：{}", date);
        calendar.setTime(date);
        calendar.add(Calendar.YEAR, -3);
        log.info("三年前的时间为：{}", calendar.getTime());
        // 查询用户是否 近3逾期2次以上（金额小于1000元，3天内还清的除外）
        List<SeLoanRecord> seLoanRecords = seLoanRecordMapper.selectRecordById(userId, calendar.getTime(), date);
        // 逾期数量
        AtomicInteger count = new AtomicInteger(seLoanRecords.size());
        seLoanRecords.stream().forEach(item -> {
            if ((Integer.parseInt(item.getQuota()) <= 1000) && ((item.getCreateAt().getTime() - item.getReturnTime().getTime()) <= 3)) {
                // 如果 小于 1000 并且 3 天内还完
                count.getAndAdd(-1);
            }
        });
        if (count.get() >= 2) {
            return false;
        }
        return true;
    }
}
